package net.xiangcaowuyu.springcloud.alibaba.config;

import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 博客：https://www.xiangcaowuyu.net
 * Description:
 *
 * @Author: 香草物语
 * DateTime: 2021-07-27 20:36
 */
public class CustomerBalancerRule implements IRule {

    private ILoadBalancer balancer = new BaseLoadBalancer();

    @Override
    public Server choose(Object object) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String name = request.getParameter("name");
        List<Server> servers = balancer.getAllServers();
        if ("zhangsan".equals(name)) {
            if (servers.stream().anyMatch(e -> e.getPort() == 9001)) {
                return servers.stream().filter(e -> e.getPort() == 9001).collect(Collectors.toList()).get(0);
            }
            return servers.get(0);
        }
        return servers.get(1);
    }

    @Override
    public void setLoadBalancer(ILoadBalancer iLoadBalancer) {
        this.balancer = iLoadBalancer;
    }

    @Override
    public ILoadBalancer getLoadBalancer() {
        return this.balancer;
    }
}
